from paddleocr import PaddleOCR
from PIL import Image
import cv2
import numpy as np
import os
from datetime import datetime

# 初始化OCR模型
ocr = PaddleOCR(use_angle_cls=False, lang='ch', show_log=False)

def crop_nutrition_content(image_path: str, output_dir ="static/preprocess/crop") -> str:
    # 加载图像
    image = cv2.imread(image_path)
    ocr_result = ocr.ocr(image_path, cls=False)

    # 寻找关键文本的最大 y2（bottom）
    crop_start_y = 0
    keywords = ['营养成分表', '项目', '每份', 'NRV%']

    for line in ocr_result[0]:
        text = line[1][0]
        box = line[0]  # 四个点 [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
        ys = [pt[1] for pt in box]

        if any(kw in text for kw in keywords):
            max_y = max(ys)
            if max_y > crop_start_y:
                crop_start_y = max_y

    # 向下裁剪，保留下方部分
    h, w, _ = image.shape
    rough_crop = image[int(crop_start_y)+30:, :]  # +5 可微调裁剪间距

    # Step 2: 精确裁剪（从内容文字框中提取左右下边界）
    temp_path = output_dir + "/temp_crop.png"
    cv2.imwrite(temp_path, rough_crop)
    new_ocr_result = ocr.ocr(temp_path, cls=False)

    height, width, _ = rough_crop.shape
    x_min, x_max = width, 0
    y_max = 0

    for line in new_ocr_result[0]:
        box = line[0]
        xs = [pt[0] for pt in box]
        ys = [pt[1] for pt in box]
        x_min = min(x_min, min(xs))
        x_max = max(x_max, max(xs))
        y_max = max(y_max, max(ys))

    # 增加微小margin，避免裁过头
    margin = 3
    x_min = max(x_min - margin, 0)
    x_max = min(x_max + margin, width)
    y_max = min(y_max + margin, height)

    # 防止非法切片
    if x_min >= x_max or y_max <= 0:
        raise ValueError("OCR结果无效或坐标非法，裁剪区域为空。")

    final_crop = rough_crop[0:int(y_max), int(x_min):int(x_max)]

    # 保存最终结果
    os.makedirs(output_dir, exist_ok=True)
    filename = f"crop_content_{datetime.now().strftime('%Y%m%d%H%M%S')}.png"
    output_path = os.path.join(output_dir, filename)
    cv2.imwrite(output_path, final_crop)

    # 清理临时文件
    if os.path.exists(temp_path):
        os.remove(temp_path)

    return output_path